"""
日志面板 - 右侧日志显示区域组件
实时显示应用运行日志
"""

from PyQt5.QtWidgets import (QWidget, QVBoxLayout, QTextEdit, QGroupBox)
from PyQt5.QtCore import pyqtSignal
from PyQt5.QtGui import QTextCursor, QFont, QColor
import logging
import os
from datetime import datetime


class LogPanel(QWidget):
    """日志面板"""
    
    # 信号定义
    log_cleared = pyqtSignal()  # 日志清空信号
    
    def __init__(self, logger_manager, parent=None):
        super().__init__(parent)
        self.logger_manager = logger_manager
        self.logger = logging.getLogger(__name__)
        
        # 日志更新标志（确保有日志时会刷新）
        self.log_updated = False
        

        

        
        # 日志颜色配置 - 适合白底的颜色
        self.log_colors = {
            'INFO': QColor(0, 0, 0),         # 黑色
            'WARNING': QColor(204, 102, 0),  # 深橙色
            'ERROR': QColor(204, 0, 0),      # 深红色
            'DEBUG': QColor(102, 102, 102),  # 深灰色
            'SUCCESS': QColor(0, 128, 0),    # 绿色
            'TRADE_EXECUTED': QColor(0, 150, 0),    # 深绿色 - 已执行交易
            'TRADE_PENDING': QColor(150, 0, 0),     # 深红色 - 待成交交易
            'TRADE_UPDATED': QColor(204, 102, 0),   # 橙色 - 状态变更
        }
        
        self.setup_ui()
    
    def setup_ui(self):
        """初始化UI"""
        layout = QVBoxLayout(self)
        layout.setContentsMargins(10, 10, 10, 10)
        layout.setSpacing(10)
        

        
        # 日志显示区域
        log_group = self.create_log_display_group()
        layout.addWidget(log_group)
        

        
        self.logger.info("日志面板UI初始化完成")
    

    def create_log_display_group(self):
        """创建日志显示组"""
        group = QGroupBox("日志内容")
        layout = QVBoxLayout(group)
        
        # 日志文本显示区域
        self.log_text_edit = QTextEdit()
        self.log_text_edit.setReadOnly(True)
        
        # 设置等宽字体
        font = QFont("Consolas")
        if not font.exactMatch():
            font = QFont("Courier New")
        font.setPointSize(9)
        self.log_text_edit.setFont(font)
        
        # 设置样式 - 白底黑字
        self.log_text_edit.setStyleSheet("""
            QTextEdit {
                background-color: #ffffff;
                color: #000000;
                border: 1px solid #cccccc;
                padding: 5px;
                font-family: 'Consolas', 'Courier New', monospace;
            }
        """)
        
        layout.addWidget(self.log_text_edit)
        
        return group
    


    

    def update_logs(self):
        """更新日志显示（静默更新，不干扰用户滚动）"""
        try:
            # 获取日志内容（固定使用app.log）
            log_content = self.logger_manager.get_log_content(
                'app.log', 
                lines=500  # 显示最后500行
            )
            
            if log_content:
                # 保存当前滚动位置，更新后恢复
                scrollbar = self.log_text_edit.verticalScrollBar()
                current_position = scrollbar.value()
                
                # 更新文本内容
                self.update_text_with_colors(log_content)
                
                # 恢复用户的滚动位置，不干扰用户查看
                scrollbar.setValue(current_position)
            
        except Exception as e:
            self.logger.error(f"更新日志显示失败: {e}")
    
    def update_text_with_colors(self, content):
        """更新文本并设置颜色"""
        # 清空当前内容
        self.log_text_edit.clear()
        
        # 按行处理日志
        lines = content.strip().split('\n')
        
        cursor = self.log_text_edit.textCursor()
        
        for line in lines:
            if not line.strip():
                continue
            
            # 检测日志级别并设置颜色
            color = self.get_line_color(line)
            
            # 设置文本格式
            char_format = cursor.charFormat()
            char_format.setForeground(color)
            cursor.setCharFormat(char_format)
            
            # 插入文本
            cursor.insertText(line + '\n')
    
    def get_line_color(self, line):
        """获取日志行的颜色"""
        line_upper = line.upper()
        
        # 首先检查错误和警告（优先级最高）
        if 'ERROR' in line_upper or '❌' in line:
            return self.log_colors['ERROR']
        elif 'WARNING' in line_upper or '⚠️' in line:
            return self.log_colors['WARNING']
        elif 'DEBUG' in line_upper:
            return self.log_colors['DEBUG']
        # 然后检查交易相关的日志标记
        elif '🟢' in line or ('交易执行' in line or '交易更新' in line):
            return self.log_colors['TRADE_EXECUTED']
        elif '🔴' in line or ('交易记录' in line and '待执行' in line) or ('记录更新' in line and '待执行' in line):
            return self.log_colors['TRADE_PENDING']
        elif '🟡' in line or '状态变更' in line or ('从待执行变为已执行' in line or '批量状态变更' in line):
            return self.log_colors['TRADE_UPDATED']
        # 最后检查成功标记
        elif '✅' in line or 'SUCCESS' in line_upper:
            return self.log_colors['SUCCESS']
        else:
            return self.log_colors['INFO']
    

    def add_log_message(self, level, message):
        """直接添加日志消息（用于实时日志，静默更新不影响用户滚动）"""
        try:
            current_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
            log_line = f"{current_time} - {level} - {message}"
            
            # 保存当前滚动位置
            scrollbar = self.log_text_edit.verticalScrollBar()
            current_position = scrollbar.value()
            was_at_bottom = current_position == scrollbar.maximum()
            
            # 获取颜色
            color = self.log_colors.get(level.upper(), self.log_colors['INFO'])
            
            # 添加到文本框
            cursor = self.log_text_edit.textCursor()
            cursor.movePosition(QTextCursor.End)
            
            char_format = cursor.charFormat()
            char_format.setForeground(color)
            cursor.setCharFormat(char_format)
            
            cursor.insertText(log_line + '\n')
            
            # 只有当用户本来就在底部时，才滚动到最新日志
            # 否则保持用户当前的浏览位置不变
            if was_at_bottom:
                self.log_text_edit.moveCursor(QTextCursor.End)
            else:
                # 尝试恢复用户的滚动位置
                scrollbar.setValue(current_position)
            
        except Exception as e:
            print(f"添加日志消息失败: {e}")
    
    def get_visible_log_content(self):
        """获取当前可见的日志内容"""
        return self.log_text_edit.toPlainText()
    
    def save_log_to_file(self, file_path):
        """保存日志到文件"""
        try:
            content = self.get_visible_log_content()
            with open(file_path, 'w', encoding='utf-8') as f:
                f.write(content)
            
            self.logger.info(f"日志已保存到: {file_path}")
            return True
            
        except Exception as e:
            self.logger.error(f"保存日志文件失败: {e}")
            return False
